#!/bin/bash
if [ -n "$GITHUB_PROXY" ]; then
    export CONDA_CHANNELS='https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main,https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r,https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2'
    export PIP_INDEX_URL='https://mirrors.aliyun.com/pypi/simple/'
fi

source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/alias.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_run.sh"
source "${LMD_BASE_INSTALL_SCRIPT_DIR}/global/conda_and_pip_settings.sh"

APP_TARGET_DIR_NAME="LatentSync"

export CURRENT_APP_PATH="$LMD_APPS_DIR/$APP_TARGET_DIR_NAME"
echo "App Dir: ${CURRENT_APP_PATH}"

if [ -d "$CURRENT_APP_PATH" ]; then
    echo "App Dir: "$CURRENT_APP_PATH
else
    echo "Error, App Dir dose not exist, please retry. "$CURRENT_APP_PATH
    exit 1
fi

cd "$CURRENT_APP_PATH"
conda --version

if [ -z "$HF_ENDPOINT" ] && [ -n "$HF_MIRROR" ]; then
    export HF_ENDPOINT="$HF_MIRROR"
fi

export GRADIO_TEMP_DIR="$CURRENT_APP_PATH/temp_gradio"
CONDA_PREFIX="./venv"


export HF_HOME="./tmp_hf_home"
export TORCH_HOME="./tmp_torch_home"

transformers_cache_dir="$CURRENT_APP_PATH/tmp_hf_home_by_modelscope"
detect_model_dir="$transformers_cache_dir/hub/models--stabilityai--sd-vae-ft-mse"
if [ -d "$detect_model_dir" ]; then
  echo "found hf models in $transformers_cache_dir"
  export TRANSFORMERS_OFFLINE=1
  export HF_HUB_DISABLE_SYMLINKS=1
  export TRANSFORMERS_CACHE="$transformers_cache_dir/hub"
  export HF_HOME="$transformers_cache_dir"
fi

conda run -p $CONDA_PREFIX --no-capture-output python gradio_app.py
